package cn.itcast.filter16.filter;



import cn.itcast.filter16.entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet-1", value = "/LoginServlet-1")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+password);
        // 检查用户名和密码
        if ("chenyu".equals(username) && "202212390606".equals(password)) {
            // 登录成功
            // 将user对象写入session域
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            request.getSession().setAttribute("user", user);

            // 发送自动登录的Cookie
            // 获取自动登录的时间参数
            String autologin = request.getParameter("autologin");
            // 如果用户设置了自动登录时间，则设置cookie的有效时间
            if (autologin != null) {
                // 注意cookie中的密码要加密
                Cookie cookie = new Cookie("autologin", username + "." + password);
                cookie.setMaxAge(Integer.parseInt(autologin));
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
            // 重定向到首页
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            request.setAttribute("errorMsg", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
